package com.syx.util;

import com.syx.controller.LogController;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.*;

public class FileUpload2 {

    private static final int BUFFER_SIZE = 100 * 1024;
    private static final Logger logger = Logger.getLogger(LogController.class);
    
    public static String plupload(@RequestParam MultipartFile file, HttpServletRequest request) {
       String path="";
        try {
            String name = request.getParameter("name");
            Integer chunk = 0, chunks = 0;
            if(null != request.getParameter("chunk") && !request.getParameter("chunk").equals("")){
                chunk = Integer.valueOf(request.getParameter("chunk"));
            }
            if(null != request.getParameter("chunks") && !request.getParameter("chunks").equals("")){
                chunks = Integer.valueOf(request.getParameter("chunks"));
            }
            logger.info("chunk:[" + chunk + "] chunks:[" + chunks + "]");
            //检查文件目录，不存在则创建
            String relativePath = "/plupload/files/";
            String realPath = request.getSession().getServletContext().getRealPath("");
            File folder = new File(realPath + relativePath);
            if (!folder.exists()) {
                folder.mkdirs();
            }

            //目标文件
            File destFile = new File(folder, name);
            //文件已存在删除旧文件（上传了同名的文件）
            if (chunk == 0 && destFile.exists()) {
                destFile.delete();
                destFile = new File(folder, name);
            }
            //合成文件
            appendFile(file.getInputStream(), destFile);
            if (chunk == chunks - 1) {
                logger.info("上传完成");
            }else {
                logger.info("还剩["+(chunks-1-chunk)+"]个块文件");
            }
            path=(relativePath+name).substring(1);

        } catch (IOException e) {
            logger.error(e.getMessage());
        }

        return path;
    }

    private static void appendFile(InputStream in, File destFile) {
        OutputStream out = null;
        try {
            // plupload 配置了chunk的时候新上传的文件append到文件末尾
            if (destFile.exists()) {
                out = new BufferedOutputStream(new FileOutputStream(destFile, true), BUFFER_SIZE);
            } else {
                out = new BufferedOutputStream(new FileOutputStream(destFile),BUFFER_SIZE);
            }
            in = new BufferedInputStream(in, BUFFER_SIZE);

            int len = 0;
            byte[] buffer = new byte[BUFFER_SIZE];
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            try {
                if (null != in) {
                    in.close();
                }
                if(null != out){
                    out.close();
                }
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
    }
}
